<template>
  <div>
    <div class="toptop" style :style="'width: 1200px;'">
      <div>
        <span>
          <span style="margin-right: 24px;">公司</span>
          <el-select v-model="companyId" placeholder="请选择" filterable>
            <el-option v-for="(item, index) in companyIdList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </span>
      </div>
      <el-button size="small" class="bottom_all" @click="savefrequency()">保存</el-button>
    </div>
    <div class="info" style="display: flex;max-width:1200px;">
      <!-- 切换物料，标号，等级 -->
      <div class="left">
        <div class="nav">
          <template v-for="(item, index) in leftList">
            <div :key="index" :style="'width:' + 100 / leftList.length + '%'" :class="item.value == leftIndex ? 'left-active' : ''" @click="changeindex(item.value)">{{ item.text }}</div>
          </template>
        </div>
        <!-- 物料强度性能数据 -->
        <!-- <div class="radio leftitem">
          <el-radio-group v-model="showleftitemId" @change="changeleft">
            <template v-for="(item, index) in leftitemList">
              <div :key="index" class="radio-bg">
                <el-radio :label="item.id">{{ item.name }}</el-radio>
              </div>
            </template>
          </el-radio-group>
        </div> -->
        <div class="radio leftitem">
          <div style="padding:10px 0;">
            {{['','原物料名称','强度等级','规范性能等级'][leftIndex]}}:
          </div> 
          <el-select v-model="showleftitemId" filterable placeholder="请选择" @change="changeRaw">
            <el-option v-for="(item, index) in leftitemList" :key="index" :label="item.name" :value="item.name"></el-option>
          </el-select>
          <div v-show="leftIndex==1">
            <div style="padding:10px 0;">
              规格:
            </div> 
            <el-select v-model="specification" filterable placeholder="请选择" @change="changeleft">
              <el-option v-for="item in specificationList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="center"></div>
      <div class="right" style="max-width:850px;">
        <div class="items">
          <div v-if="leftIndex!=3" class="item">
            <div class="item-title">检验类别</div>
            <div class="radio">
              <el-radio-group v-model="showleftId" @change="changeleftId">
                <template v-for="(item, index) in leftIdList">
                  <div :key="index" class="radio-bg">
                    <el-radio :label="item.id">{{ item.name }}</el-radio>
                  </div>
                </template>
              </el-radio-group>
            </div>
          </div>
          <div class="item-hr"></div>
          <div v-if="leftIndex!=1" class="item">
            <div class="item-title">检验前置条件</div>
            <div class="radio">
              <div style="padding:10px 0 0 0">
                <el-checkbox v-model="orderStatus" :true-label="1" :false-label="0" @change="change">
                  <div style="word-break:break-all;">
                    <div>订单计划量不小于</div>
                    <el-input v-model="orderNum" style="width:160px;margin:10px 0 0 0" placeholder="请输入" clearable @change="change">
                      <span slot="suffix" style="line-height:36px">方</span>
                    </el-input>
                  </div>
                </el-checkbox>
              </div>
              <div style="padding:20px 0 0 0">
                <el-checkbox v-model="productionStatus" :true-label="1" :false-label="0" @change="change">
                  <div>单车生产量不小于</div>
                  <el-input v-model="production" style="width:160px;margin:10px 0 0 0" placeholder="请输入" clearable @change="change">
                    <span slot="suffix" style="line-height:36px">方</span>
                  </el-input>
                </el-checkbox>
              </div>
            </div>
          </div>
          <div class="item-hr"></div>
          <div class="item" style="width:300px;flex:none;">
            <div class="item-title">检测频率</div>
            <div class="radio">
              <el-checkbox-group v-model="rightId" @change="change">
                <template v-for="(item, index) in rightIdList">
                  <el-checkbox :key="index" :label="item.id" style="margin-bottom:10px;">
                    每<el-input-number v-model="item.content" :controls="false" :precision="0" style="width:80px;margin:0 10px;" @change="change"></el-input-number>
                    {{item.itemName}}
                  </el-checkbox>
                </template>
              </el-checkbox-group>
              <template v-if="leftIndex!==1">
                <el-checkbox v-model="IntervalState" @change="change">
                  <div>累计生产量：</div>
                </el-checkbox>
                <template v-for="(item,index) in stateList">
                  <div :key="index">
                    <div v-if="index==0" style="margin-top:20px;position: relative;">
                      <div class="text12">
                        <div>小于</div>
                        <el-input v-model="item.topValue" type="Number" placeholder="请输入" style="width:90px" @change="change"></el-input>
                        <div>方</div>
                      </div>
                      <div class="text12">
                        <div>每</div>
                        <el-input v-model="item.content" style="width:90px" type="Number" placeholder="请输入" clearable @change="change"></el-input>
                        <div>方检验</div>
                      </div>
                    </div>
                    <div v-else-if="index==(stateList.length-1)" style="margin-top:20px;position: relative;">
                      <div class="text12">
                        <div>大于</div>
                        <div v-show="false">{{item.belowValue=stateList[index-1].topValue}}</div>
                        <el-input v-model="item.topValue" type="Number" placeholder="请输入" style="width:90px" @change="Number(item.topValue)<=Number(stateList[index-1].topValue)?item.topValue=Number(stateList[index-1].topValue)+1:'',change"></el-input>
                        <div>方</div>
                      </div>
                      <div class="text12">
                        <div>每</div>
                        <el-input v-model="item.content" style="width:90px" type="Number" placeholder="请输入" clearable @change="change"></el-input>
                        <div>方检验</div>
                      </div>
                      <div class="newbot">
                        <el-button type="success" icon="icon iconfont iconicon_button_add" circle @click="addItem()"></el-button>
                        <!-- <el-button type="success" circle size="mini" @click="addItem()">
                        <i class="icon iconfont iconicon_button_add" style="font-size:12px;color;#ffffff"></i>
                      </el-button> -->
                      </div>
                    </div>
                    <div v-else style="margin-top:20px; position: relative;">
                      <div class="text12">
                        <div>
                          <span style="padding-right:5px"> {{item.belowValue=stateList[index-1].topValue}}</span>
                          至
                        </div>
                        <el-input v-model="item.topValue" type="Number" placeholder="请输入" style="width:90px" @change="Number(item.topValue)<=Number(stateList[index-1].topValue)?item.topValue=Number(stateList[index-1].topValue)+1:'',change"></el-input>
                        <div>方</div>
                      </div>
                      <div class="text12">
                        <div>每</div>
                        <el-input v-model="item.content" style="width:90px" type="Number" placeholder="请输入" clearable @change="change"></el-input>
                        <div>方检验</div>
                      </div>
                      <div class="newbot">
                        <div style="padding-top:5px">
                          <el-button type="danger" icon="icon iconfont iconicon_button_delete" circle @click="delItem(item,index)"></el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDicType } from "@/api/common.js";
import { getListByTypeId } from "@/api/common.js";
import {
  getFirmDetection,
  getStationTest,
  saveStationTest,
  getSpecificatioByName,
  // saveTestFrequency,
} from "@/api/basicConfig/CPYquality.js";
import { permissionsCompanyList } from "@/api/common.js";
let oldList = []
export default {
  data() {
    return {
      leftList: [
        {
          text: "原物料",
          value: 1,
        },
        {
          text: "强度等级",
          value: 2,
        },
        {
          text: "规范性能等级",
          value: 3,
        },
      ],
      leftIndex: 1,
      companyId: "",
      companyIdList: [],
      /**
       * loading为true时代表可以保存
       * loading为true时代表有数据变化
      */
      loading: false,
      /**物料标号等级*/
      leftitemList: [],
      leftitemId: "",
      showleftitemId: "",
      /**检验类别*/
      leftIdList: [],
      showleftId: "",
      leftId: "",
      /**检验前置条件*/
      orderStatus: 0,
      orderNum: null,
      productionStatus: 0,
      production: null,
      /**检测频率*/
      rightIdList: [{
        itemName: "车",
        id: "1",
        content: ''
      },
      {
        itemName: "小时",
        id: "4",
        content: ''
      }],
      rightId: [],
      IntervalState: false,
      stateList: [
        { belowValue: '', topValue: '', frequencyId: 5, content: '' },
        { belowValue: '', topValue: '', frequencyId: 5, content: '' }
      ],
      specification: '',
      specificationList: [],
      rawId: '',
    };
  },
  async created() {
    this.companyIdList = await permissionsCompanyList()
    this.companyId = this.companyIdList[0].id
  },
  watch: {
    /**切换物料强度等级*/
    leftIndex: {
      handler() {
        let _this = this;
        this.clearCategory()
        this.clearRight()
        _this.showleftitemId = ''
        _this.leftitemId = ''
        _this.leftIdList = []
        switch (_this.leftIndex) {
          case 1: {
            _this.rightIdList = [{
              itemName: "车",
              id: "1",
              content: ''
            },
            {
              itemName: "吨",
              id: "2",
              content: ''
            },
            {
              itemName: "方",
              id: "3",
              content: ''
            },
            {
              itemName: "小时",
              id: "4",
              content: ''
            }]
            getDicType({
              code: "MATname",
            }).then((res) => {
              _this.leftitemList = res.data.items.map((res) => {
                let obj = {
                  id: res.id,
                  name: res.itemName,
                };
                return obj;
              });
            });
            return;
          }
          case 2: {
            getListByTypeId({ typeId: 1 }).then((res) => {
              _this.leftitemList = res.data;
            });
            _this.rightIdList = _this.$options.data().rightIdList
            return;
          }
          case 3: {
            getListByTypeId({ typeId: 2 }).then((res) => {
              _this.leftitemList = res.data;
            });
            _this.rightIdList = _this.$options.data().rightIdList
            return;
          }
        }
      },
      deep: false,
      immediate: true,
    },
    /**选择公司,选择物料强度等级获取检验类别
     * 并清空频率
    */
    dateRange() {
      if (
        this.companyId == "" ||
        this.leftIndex == "" ||
        this.leftitemId == ""
      ) {
        return;
      }
      let data = new Object();
      data.type = this.leftIndex;
      data.all = 1
      data.companyId = this.companyId;
      if (this.leftIndex == 1) {
        data.rawId = this.rawId;
        data.specification = this.specification;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      if (this.leftIndex !== 3) {
        getFirmDetection(data).then((res) => {
          this.leftIdList = res.data;
          this.clearCategory()
        });
      } else {
        this.clearCategory()
      }
      this.clearRight()
    },
    companyId() {
      this.showleftitemId = ''
      this.eftitemId = ''
    },
  },
  computed: {
    dateRange() {
      const leftitemId = this.leftitemId
      const companyId = this.companyId
      return { companyId, leftitemId }
    },
  },
  methods: {
    changeRaw () {
      this.specification = '';
      this.rawId = this.leftitemList.find(item => item.name === this.showleftitemId).id;
      getSpecificatioByName({name: this.showleftitemId}).then(res => {
        if (res.code === 1001) {
          this.specificationList = res.data;
        }
      })
      if (this.leftIndex == 2) {
        this.leftitemId = this.rawId;
      }
    },
    /**切换物料，标号，等级类别*/
    changeindex(a) {
      let _this = this;
      if (_this.loading) {
        this.$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            _this.savefrequency();
          })
          .catch(() => {
            _this.leftIndex = a;
            _this.loading = false;
          });
        return;
      }
      _this.leftIndex = a;
    },
    /**选择物料，标号，等级*/
    changeleft() {
      let _this = this;
      if (_this.loading) {
        _this
          .$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            cancelButtonClass: "bottom_all_two",
            confirmButtonClass: "bottom_all",
            type: "warning",
          })
          .then(() => {
            _this.showleftitemId = _this.leftitemId;
            _this.savefrequency();
          })
          .catch(() => {
            _this.leftitemId = _this.showleftitemId;
            if (_this.leftIndex == 3) {
              _this.getrightId()
            }
            _this.loading = false;
          });
        return;
      }
      _this.leftitemId = _this.showleftitemId;
      if (_this.leftIndex == 3) {
        _this.getrightId()
      }
    },
    /**选择检验类别*/
    changeleftId() {
      let _this = this;
      if (_this.loading) {
        _this
          .$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            cancelButtonClass: "bottom_all_two",
            confirmButtonClass: "bottom_all",
            type: "warning",
          })
          .then(() => {
            _this.showleftId = _this.leftId;
            _this.savefrequency();
          })
          .catch(() => {
            _this.leftId = _this.showleftId;
            _this.getrightId();
            _this.loading = false;
          });
        return;
      }
      _this.leftId = _this.showleftId;
      _this.getrightId();
    },
    change() {
      if (this.leftIndex == 3 && this.leftitemId) {
        this.loading = true
      }
      if (this.leftitemId && this.leftId && this.leftIndex !== 3) {
        this.loading = true
      }

    },
    /**保存数据*/
    savefrequency() {
      let _this = this;
      function setdata(content, frequencyId, frequency, id) {
        this.id = id
        this.companyId = _this.companyId
        this.content = content
        this.contractId = 0
        this.stationId = 0
        this.frequency = frequency
        this.frequencyId = frequencyId
        this.materialsId = _this.rawId
        this.specification = _this.specification;
        this.materialsName = _this.leftitemList.find(res => (res.id == _this.leftitemId))?.name
        this.materialsType = _this.leftIndex
        this.orderNum = _this.orderNum
        this.production = _this.production
        this.qualityDetection = _this.leftIdList.find(res => (res.id == _this.leftId))?.name
        this.qualityDetectionId = _this.leftId
        this.checkOrderNum = _this.orderStatus
        this.checkProduction = _this.productionStatus
      }
      let arr = []
      _this.rightId.forEach((v) => {
        arr.push(
          new setdata(
            _this.rightIdList.find(res => (res.id == v))?.content,
            v,
            _this.rightIdList.find(res => (res.id == v))?.itemName,
            oldList.find(res => (res.frequencyId == v))?.id
          ),
        )
      })
      if (_this.IntervalState) {
        let content = _this.stateList.map(res => ({ num: Number(res.topValue), value: res.content }))
        console.log(content);
        arr.push(
          new setdata(
            JSON.stringify(content),
            5,
            '累计生产量',
            oldList.find(res => (res.frequencyId * 1 == 5))?.id
          )
        )
      }
      if (_this.leftitemId == '') {
        _this.$message.warning('请选择原物料、强度等级或规范性能等级')
        return
      }
      if (_this.leftIndex !== 3 && _this.leftId == '') {
        _this.$message.warning('请选择检验类别')
        return
      }
      if (oldList.length == 0 && arr.length == 0) {
        _this.$message.warning('请选择检验频率')
        return
      }

      let allHasData = arr.filter((item) => (
        oldList.some((items) => (item.id == items.id))
      ))
      let deleteData = oldList.filter((item) => (
        !allHasData.some((items) => (item.id == items.id))
      ))
      deleteData.forEach(item => { item.status = 0 })
      saveStationTest([...arr, ...deleteData]).then((res) => {
        if (res.code * 1 === 1001) {
          _this.$message.success("保存成功")
          _this.getrightId()
        }
      });
    },
    /**选择检验类别时获取关联数据*/
    getrightId() {
      let _this = this;
      let data = new Object();
      data.materialsType = _this.leftIndex;
      data.companyId = _this.companyId;
      data.materialsId = _this.rawId;
      data.specification = _this.specification;
      data.stationId = 0
      data.contractId = 0
      data.qualityDetectionId = _this.leftId
      getStationTest(data).then((res) => {
        _this.loading = false
        /*获取关联数据*/
        if (res.data.length !== 0) {
          oldList = JSON.parse(JSON.stringify(res.data))
          /**回显每...*/
          _this.rightId = res.data.filter(res => (res.frequencyId * 1 !== 5)).map(item => (item.frequencyId))
          if (this.leftIndex !== 1) {
            this.rightIdList = [{
              itemName: "车",
              id: "1",
              content: res.data.find(res => (res.frequencyId == 1))?.content
            },
            {
              itemName: "小时",
              id: "4",
              content: res.data.find(res => (res.frequencyId == 4))?.content
            }]
          } else {
            this.rightIdList = [{
              itemName: "车",
              id: "1",
              content: res.data.find(res => (res.frequencyId == 1))?.content
            },
            {
              itemName: "吨",
              id: "2",
              content: res.data.find(res => (res.frequencyId == 2))?.content
            },
            {
              itemName: "方",
              id: "3",
              content: res.data.find(res => (res.frequencyId == 3))?.content
            },
            {
              itemName: "小时",
              id: "4",
              content: res.data.find(res => (res.frequencyId == 4))?.content
            }]
          }

          /**回显检验前置条件*/
          _this.orderStatus = res.data[0].checkOrderNum
          _this.orderNum = res.data[0].orderNum
          _this.productionStatus = res.data[0].checkProduction
          _this.production = res.data[0].production
          /**回显累计生产量*/
          let content = res.data.find(res => (res.frequencyId == 5))
          _this.IntervalState = Boolean(content)
          if (!content?.content) {
            _this.stateList = _this.$options.data().stateList
            return
          }
          _this.stateList = JSON.parse(content?.content).map(res => (
            { belowValue: '', topValue: res.num, frequencyId: 5, content: res.value }
          ))
          return
        }
        _this.clearRight()
      });
    },
    /**清空检验类别*/
    clearCategory() {
      this.showleftId = "";
      this.rightId = [];
      this.leftId = "";
    },
    /**清空检验前置条件和检测频率*/
    clearRight() {
      let _this = this
      oldList = []
      _this.rightId = []
      // _this.rightIdList = _this.$options.data().rightIdList
      _this.IntervalState = false
      _this.stateList = _this.$options.data().stateList
      _this.orderStatus = 0
      _this.orderNum = null
      _this.productionStatus = 0
      _this.production = null
    },
    /*累计生产量的增删*/
    addItem() {
      this.stateList.push(
        { belowValue: '', topValue: '', frequencyId: 5, content: '' }
      )
    },
    delItem(item, index) {
      if (item.id) {
        item.status = 0
        return
      }
      this.stateList.splice(index, 1)
    },
  },
};
</script>

<style lang="scss" scoped>
.center {
  width: 24px;
  height: 100%;
}
.left {
  border: 1px solid rgba(225, 229, 237, 1);
  flex: 2;
  border-radius: 4px;
}
.nav {
  padding: 0 20px;
  height: 56px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  background: #e1e5ed;
  color: #000000;
  > div {
    font-size: 12px;
    font-weight: bold;
    height: 48px;
    //width: 50%;
    @include discen;
    cursor: pointer;
  }

  .left-active {
    color: $bg_color;
    border-radius: 8px 8px 0px 0px;
    background: #ffffff;
  }
}
.radio-bg:hover .block {
  display: inline-block;
}
.block {
  display: none;
}
.active {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: red;
  margin: 0 5px;
}
.none {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin: 0 5px;
  background: #808080;
}
.toptop {
  padding: 20px 20px 0 20px;
  @include discen_al;
  justify-content: space-between;
}
.info {
  height: 705px;
  padding: 20px;
}
.items {
  display: flex;
  height: 100%;
}
.item {
  flex: 1;
  border: 1px solid rgba(225, 229, 237, 1);
  border-radius: 4px;
  .item-title {
    color: #000000;
    background: #e1e5ed;
    font-size: 14px;
    @include discen;
    height: 56px;
    font-weight: bold;
  }
}
.el-radio {
  margin-right: 5px;
}
.radio {
  padding: 20px;
  .radio-bg {
    height: 28px;
  }
  i {
    color: #808080;
    margin-left: 5px;
  }
  i:hover {
    color: $bg_color;
  }
}
.item-hr {
  width: 20px;
  height: 20px;
}
.right {
  flex: 5;
  border-radius: 4px;
}
.radio {
  overflow: auto;
  padding: 20px;
  height: calc(100% - 56px);
  .radio-bg {
    height: 28px;
  }
}
.radio::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}
.radio::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
.radio::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}
.radio::-webkit-scrollbar-thumb:hover {
  background: $bg_color;
}
.radio::-webkit-scrollbar-corner {
  background: $bg_color;
}
.text12 {
  display: flex;
  align-items: center;
  > div:first-child {
    width: 50px;
  }
  > div:last-child {
    padding-left: 20px;
  }
}
.newbot {
  position: absolute;
  right: 0px;
  top: 0;
}
.text12 + .text12 {
  padding-top: 5px;
}
</style>
